﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace WMS.Service.tool
{
    public class HttpRequest
    {
        private static string HttpUrl = "127.0.0.1";

        #region Get请求
        public static JsonData Get(string uri)
        {
            JsonData jsonData = new JsonData();
            try
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = string.Format("{0}/{1}", HttpUrl, uri);
                //创建Web访问对  象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(uri);
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                jsonData = Json.ToObject<JsonData>(returnXml);
            }
            catch (WebException ex)
            {
                jsonData.code = 3;
                jsonData.msg = "网络连接错误!" + ex.Message;
            }

            return jsonData;
        }

        public static JsonData GetT(string uri)
        {
            JsonData jsonData = new JsonData();
            try
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = string.Format("{0}/{1}", HttpUrl, uri);
                //创建Web访问对  象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(uri);
                myRequest.Headers.Add("Authorization", "this token"); // 带token的get请求
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                jsonData = Json.ToObject<JsonData>(returnXml);
            }
            catch (WebException ex)
            {
                jsonData.code = 3;
                jsonData.msg = "网络连接错误!" + ex.Message;
            }

            return jsonData;
        }

        #endregion

        #region Post请求
        public static JsonData Post(string data, string uri)
        {
            JsonData jsonData = new JsonData();
            try
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = uri;// string.Format("{0}/{1}", HttpUrl, uri);
                //创建Web访问对象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = Encoding.GetEncoding("UTF-8").GetBytes(data);

                myRequest.Method = "POST";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json";
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                //发送请求
                Stream stream = myRequest.GetRequestStream();
                stream.Write(buf, 0, buf.Length);
                stream.Close();
                //获取接口返回值
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

                //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                jsonData = Json.ToObject<JsonData>(returnXml);
            }
            catch (Exception ex)
            {
                jsonData.code = 2;
                jsonData.msg = "网络连接错误!" + ex.Message;
            }


            return jsonData;

        }
        public static String Post(Dictionary<String, Object> map, String url)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            #region 添加Post参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in map)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}:{1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString()); req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length); reqStream.Close();

            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream();
            // 获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }

            return result;
        }

        public static JsonData PostT(string data, string uri)
        {
            JsonData jsonData = new JsonData();
            try
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = uri;// string.Format("{0}/{1}", HttpUrl, uri);
                //创建Web访问对象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = Encoding.GetEncoding("UTF-8").GetBytes(data);

                myRequest.Method = "POST";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json";
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                myRequest.Headers.Add("Authorization", "this token"); // 带token的请求
                //发送请求
                Stream stream = myRequest.GetRequestStream();
                stream.Write(buf, 0, buf.Length);
                stream.Close();
                //获取接口返回值
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

                //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                jsonData = Json.ToObject<JsonData>(returnXml);
            }
            catch (Exception ex)
            {
                jsonData.code = 2;
                jsonData.msg = "网络连接错误!" + ex.Message;
            }


            return jsonData;

        }
        public class JsonData
        {
            public int code { get; set; }
            public string msg { get; set; }
            public object data { get; set; }
            public bool success { get; set; }
            public string message { get; set; }
            public string errorStack { get; set; }
        }
        #endregion

        #region 自定义Post请求

        /// <summary>
        /// 自定义post请求   获取token
        /// </summary>
        /// <param name="data">拼接参数</param>
        /// <param name="uri">请求地址</param>
        /// <returns></returns>
        public static JsonData MyPost(string data, string uri)
        {
            JsonData jsonData = new JsonData();
            try
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = uri + "?" + data;// string.Format("{0}/{1}", HttpUrl, uri);
                //创建Web访问对象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = Encoding.GetEncoding("UTF-8").GetBytes(data);

                myRequest.Method = "POST";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json";
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                myRequest.Headers.Add("Authorization", "");
                //myRequest.Headers.Add("Content-type", "application/x-www-form-urlencoded");
                myRequest.ContentType = "application/x-www-form-urlencoded";
                //发送请求
                Stream stream = myRequest.GetRequestStream();
                stream.Write(buf, 0, buf.Length);
                stream.Close();
                //获取接口返回值
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

                //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                jsonData = Json.ToObject<JsonData>(returnXml);
            }
            catch (Exception ex)
            {
                jsonData.code = 2;
                jsonData.msg = "网络连接错误!" + ex.Message;
            }


            return jsonData;

        }


        /// <summary>
        /// 自定义Post请求   获取视图数据
        /// </summary>
        /// <param name="data">请求体参数</param>
        /// <param name="uri">请求地址</param>
        /// <param name="map">请求头参数</param>
        /// <returns></returns>
        public static JsonData MyPost(string data, string uri, Dictionary<string, object> map)
        {
            JsonData jsonData = new JsonData();
            try
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = uri;// string.Format("{0}/{1}", HttpUrl, uri);
                //创建Web访问对象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = Encoding.GetEncoding("UTF-8").GetBytes(data);

                myRequest.Method = "POST";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json";
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                myRequest.Headers.Add("Authorization", "");
                //myRequest.Headers.Add("Content-type", "application/x-www-form-urlencoded");
                //myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.Headers.Add("access_token", map["access_token"].ToString());
                myRequest.Headers.Add("signature", map["signature"].ToString());
                myRequest.Headers.Add("client_id", map["client_id"].ToString());
                myRequest.Headers.Add("ucg_flag", "Y");
                myRequest.Headers.Add("repeat_check", "Y");

                //发送请求
                Stream stream = myRequest.GetRequestStream();
                stream.Write(buf, 0, buf.Length);
                stream.Close();
                //获取接口返回值
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

                //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                jsonData = Json.ToObject<JsonData>(returnXml);
            }
            catch (Exception ex)
            {
                jsonData.code = 2;
                jsonData.msg = "网络连接错误!" + ex.Message;
            }


            return jsonData;

        }

        #endregion

    }
}
